<template>
  <el-form :model="formData" size="small" :rules="rules" ref="formRef" label-width="84px">
    <el-form-item label="关联菜单">
      <el-radio-group v-model="checkStrictly" size="small" class="y-pb-2">
        <el-radio-button :label="true">父子级不关联</el-radio-button>
        <el-radio-button :label="false">父子级关联</el-radio-button>
      </el-radio-group>
      <el-tree ref="treeRef" node-key="id" show-checkbox default-expand-all :expand-on-click-node="false" :data="menuOptions" :check-strictly="checkStrictly" :props="{value: 'id', label: 'name',children: 'childList'}">
      </el-tree>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleConfirm">保存</el-button>
      <el-button @click="handleClose">关闭</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { createLoading, createMessage } from "@/utils/index.js";
import { goBack } from "@/utils/browser.js";
export default {
  name: "system_role_roleRelationMenu",
  data() {
    return {
      menuOptions: [],
      checkStrictly: true,
      formData: {
        id: "",
      },
      rules: {},
    };
  },
  methods: {
    handleConfirm() {
      this.$refs.formRef.validate(async (isOk) => {
        if (!isOk) {
          return createMessage("请完成必填项的填写与选择");
        }
        this.$refs.treeRef.getCheck
        const params = {
          roleId: this.formData.id,
          menuIds: this.$refs.treeRef.getCheckedKeys()
        };
        const loading = createLoading("保存中，请稍等");
        try {
          await this.$globalApi.role.setRoleRelationMenuApi(params);
          createMessage("保存成功", { type: "success" });
          this.$emit("refresh");
          goBack("/system/role");
        } catch (err) {
          console.log("更新报错了", err);
        } finally {
          loading.close();
        }
      });
    },
    handleClose() {
      goBack("/system/role");
    },
    async init() {
      if (!this.formData.id) {
        this.handleClose();
        return;
      }
      const loading = createLoading("正在查询角色已关联菜单信息，请稍等");
      try {
        const menuList = await this.$globalApi.menu.sysMenuListApi({});
        this.menuOptions = menuList;
        const res = await this.$globalApi.role.getRoleRelationMenuApi(
          this.formData.id
        );
        this.$refs.treeRef.setCheckedKeys(res || []);
      } catch (err) {
        console.log("查询失败了", err);
      } finally {
        loading.close();
      }
    },
  },
  mounted() {
    this.formData.id = this.$route.query.id;
    this.init();
  },
};
</script>

<style></style>